package com.ktwlrj.core.util.xpoi.util;

import com.alibaba.fastjson.JSONObject;
import com.ktwlrj.core.util.xpoi.SimpleWorkbookDesigner;
import com.ktwlrj.core.util.xpoi.SimpleWorkbookParse;
import com.ktwlrj.core.util.xpoi.model.DataSource;
import com.ktwlrj.core.util.xpoi.model.ExcelParseData;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * excel工具类
 *
 * @author zhouxuanhong
 * @date 2019-08-02 12:12
 * @since JDK1.8
 */
public class ExcelUtils {
    /**
     * 创建导出文件
     *
     * @param fieldMap     ${@link Map<String, String>}
     * @param dsList       ${@link List<Map<String, Object>>}
     * @param templatePath ${@link String}
     * @return SimpleWorkbookDesigner ${@link SimpleWorkbookDesigner}
     * @author zhouxuanhong
     * @date 2019-08-02 12:13
     */
    public static <E> SimpleWorkbookDesigner exportXls(JSONObject fieldMap, List<E> dsList, String templatePath) throws IOException, InvalidFormatException {
        ClassPathResource resource = new ClassPathResource(templatePath);
        InputStream inputStream = resource.getInputStream();
        SimpleWorkbookDesigner designer = new SimpleWorkbookDesigner();
        List<JSONObject> list = designer.listMapToJSONObject(dsList);
        designer.open(inputStream);
        DataSource dataSource = new DataSource(fieldMap, list);
        designer.setDataSource(dataSource);
        // 数据加工
        designer.process();
        return designer;
    }

    public static ExcelParseData parseExcel(String templatePath, InputStream inputStream) throws IOException, InvalidFormatException {
        ClassPathResource resource = new ClassPathResource(templatePath);
        InputStream resourceInputStream = resource.getInputStream();
        SimpleWorkbookParse workbookParse = new SimpleWorkbookParse();
        workbookParse.open(resourceInputStream);
        workbookParse.setParseWorkbook(inputStream);
        workbookParse.process();
        return workbookParse.getExcelParseData();
    }

    public static ExcelParseData parseExcel(InputStream templateFilePath, InputStream inputStream) throws IOException, InvalidFormatException {
        SimpleWorkbookParse workbookParse = new SimpleWorkbookParse();
        workbookParse.open(templateFilePath);
        workbookParse.setParseWorkbook(inputStream);
        workbookParse.process();
        return workbookParse.getExcelParseData();
    }

}
